<template>
  <div id="promotionDetailPage">
    <!-- 麵包屑導航 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />

    <!-- 消息詳情卡片 -->
    <a-space direction="vertical" style="width: 100%">
      <a-card title="基本參數" class="detail-card" :loading="loading">
        <template v-if="!loading && !promotion.id">
          <a-empty description="數據加載失敗，請重試" />
        </template>
        <template v-else>
          <a-descriptions bordered>
            <a-descriptions-item label="推廣標題">
              {{ promotion.title }}
            </a-descriptions-item>
            <a-descriptions-item label="類型">
              <template v-if="promotion.type === 1"> AIA醫療計劃 </template>
              <template v-else-if="promotion.type === 2"> 定額優惠券 </template>
              <template v-else-if="promotion.type === 3"> 折扣卡 </template>
              <template v-else> 未知 </template>
            </a-descriptions-item>
            <a-descriptions-item label="生效日期">
              {{ promotion.validFrom }}
            </a-descriptions-item>
            <a-descriptions-item label="失效日期">
              {{ promotion.validTo }}
            </a-descriptions-item>

            <a-descriptions-item label="修改人">{{
              promotion.updatedBy
            }}</a-descriptions-item>
            <a-descriptions-item label="更新時間">{{
              $formatDate(promotion.updatedAt)
            }}</a-descriptions-item>
            <a-descriptions-item label="備註">
              {{ promotion.remark ? promotion.remark : "無" }}
            </a-descriptions-item>
          </a-descriptions>
        </template>
      </a-card>
      <!-- 添加 -->
      <a-space>
        <a-button type="primary" @click="handleCreate">
          <template #icon>
            <PlusOutlined />
          </template>
          新建項
        </a-button>
      </a-space>

      <a-table
        :dataSource="promotion.items"
        :columns="promotionItemColumns"
        :loading="loading"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'code'">
            {{ record.code || "冇匹配嘅 code（默認）" }}
          </template>
          <template v-if="column.dataIndex === 'shareType'">
            <a-tag color="orange" v-if="record.shareType === 1">固定金額</a-tag>
            <a-tag color="blue" v-else>比例</a-tag>
          </template>
          <template v-if="column.dataIndex === 'staffShare'">
            <template v-if="record.shareType === 1"
              >$ {{ record.staffShare }}</template
            >
            <template v-else> {{ record.staffShare }}%</template>
          </template>
          <template v-if="column.dataIndex === 'partnerShare'">
            <template v-if="record.shareType === 1"
              >${{ record.partnerShare }}</template
            >
            <template v-else>{{ record.partnerShare }}%</template>
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleEdit(record)">修改</a-button>
            <a-button danger @click="handleDelete(record)">刪除</a-button>
          </template>
        </template>
      </a-table>
      <BackButton />
    </a-space>
    <a-modal v-model:open="showModalCreate" title="新建推廣項" :footer="null">
      <DynamicForm
        ref="createFormRef"
        :fieldConfig="createFieldConfig"
        @submit="handleCreateSubmit"
      />
    </a-modal>
    <a-modal v-model:open="showModalEdit" :footer="null">
      <template #title>
        編輯推廣項
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          ID: {{ editFormData.id }}</a-tag
        >
      </template>
      <DynamicForm
        ref="editFormRef"
        :fieldConfig="editFieldConfig"
        :formData="editFormData"
        @submit="handleEditSubmit"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { ExclamationCircleOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { useRoute } from "vue-router";
import { promotionApi } from "@/api";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";

import {
  tableColumns,
  getCreteFieldConfig,
  getEditFieldConfig,
} from "@/models/promotionItem";
import { message, Modal } from "ant-design-vue";
import BackButton from "@/components/BackButton.vue";
import DynamicForm from "@/components/DynamicForm.vue";

const route = useRoute();

// 麵包屑導航
const breadcrumbItems = [
  { url: "/promotion", name: "推廣活動" },
  { url: "", name: "推廣項詳情" },
];

// 詳情數據
const promotion = reactive({
  id: 0,
  title: "",
  type: 0,
  remark: "",
  validFrom: "",
  validTo: "",
  status: 0,
  updatedAt: "",
  items: [],
  updatedBy: "",
});
const loading = ref(true);
const promotionId = Number(route.params.id);

// 獲取詳情
const fetchDetail = async () => {
  try {
    const { data } = await promotionApi.getPromotionDetail(promotionId);
    Object.assign(promotion, data);
  } catch (error) {
    console.error("獲取詳情失敗", error);
  } finally {
    loading.value = false;
  }
};

// 初始化加載
onMounted(() => {
  fetchDetail();
});

const promotionItemColumns = tableColumns;
// 新建
const createFieldConfig = ref<Record<string, any>>({});
const showModalCreate = ref(false);
const createFormRef = ref();

const handleCreate = async () => {
  if (Object.keys(createFieldConfig.value).length === 0) {
    createFieldConfig.value = await getCreteFieldConfig(promotion.type);
  }
  showModalCreate.value = true;
};
const handleCreateSubmit = async (data: any) => {
  try {
    await promotionApi.createPromotionItem(promotionId, data);
    message.success("創建推廣項成功");
    showModalCreate.value = false;
    createFormRef.value?.resetForm();
    fetchDetail();
  } catch (error) {
    console.error("創建推廣項失敗", error);
  } finally {
    createFormRef.value.resetLoading();
  }
};

// 修改
const editFormData = reactive<any>({});
const editFieldConfig = ref<Record<string, any>>({});
const showModalEdit = ref(false);
const editFormRef = ref();

const handleEdit = async (record) => {
  Object.assign(editFormData, record);
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = await getEditFieldConfig(promotion.type);
  }
  showModalEdit.value = true;
};

const handleEditSubmit = async (data: any) => {
  try {
    await promotionApi.updatePromotionItem(promotionId, editFormData.id, data);
    message.success("修改推廣項成功");
    showModalEdit.value = false;
    fetchDetail();
  } catch (error) {
    console.error("修改項失敗", error);
  } finally {
    editFormRef.value.resetLoading();
  }
};

const handleDelete = async (record: any) => {
  Modal.confirm({
    title: "確認刪除",
    content: `確定要刪除推廣項${record.name} 嗎？`,
    okText: "確定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await promotionApi.deletePromotionItem(promotionId, record.id);
        message.success("刪除推廣項成功");
        fetchDetail();
      } catch (error) {
        console.error("刪除推廣項失敗:", error);
      }
    },
  });
};
</script>

<style scoped></style>
